package com.emergency.engine.scheduling;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.DateUtils;
import com.emergency.engine.dao.TimeLineDao;
import com.emergency.engine.domain.TimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.List;


/**
 * Created by 92924 on 2020/3/11.
 * 定时任务，用于更新时间轴
 */
@Configuration
public class SchedulingTask {

    @Autowired
    private TimeLineDao timeLineDao;

    @Autowired
    private RedisTemplate redisTemplate;

    //或直接指定时间间隔，例如：1秒
    @Scheduled(cron = "0/1 * * * * ?")
    private void configureTasks() {

        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());

        //序列化字符串
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //查询出TimeLine中状态为0的数据，把推演进度累加
        //这里查询出来的可能不止一个，所以不能直接以对象接受，要以list
        //查询时间轴缓存数据
        List<TimeLine> timeLines = (List<TimeLine>) redisTemplate.opsForValue().get("scheduled_timelines");

        //设置flag初始值为false
        boolean flag=false;

        //缓存不为空则遍历
        if (!CommonUtils.isNullOrEmpty(timeLines)) {
            //如果查询不为空，遍历list
            for (TimeLine timeLine : timeLines) {
                //推演时长获取
                long duration = DateUtils.getDateSecond( timeLine.getStartTime(),timeLine.getEndTime());
                timeLine.setProgress(timeLine.getProgress() + timeLine.getRate());
                //推演进程倒计时
                long timeSize = duration - timeLine.getProgress();
                //当进程时间大于0时更新数据库，否则跳出循环任务
                if (timeSize<=0) {
                    //停止更新数据库
                    timeLine.setStatus(2);
                    //需要删除缓存
                    flag=true;
                }
                timeLineDao.saveAndFlush(timeLine);
            }

            //通过flag判断是否删除缓存数据
            if(flag){
                redisTemplate.delete("scheduled_timelines");
            }else{
                //flag为false则插入时间轴缓存数据
                redisTemplate.opsForValue().set("scheduled_timelines",timeLines);
            }

        }
    }
}
